package com.example.config;

import com.example.dao.Roles_permissionsMapper;
import com.example.dao.User_rolesMapper;
import com.example.dao.UsersMapper;
import com.example.pojo.Roles_permissions;
import com.example.pojo.User_roles;
import com.example.pojo.Users;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class ShiroRealm extends AuthorizingRealm{

	@Autowired
	UsersMapper usersMapper; // 用户Dao

	@Autowired
	User_rolesMapper user_rolesMapper;  // 用户角色查询

	@Autowired
	Roles_permissionsMapper roles_permissionsMapper; // 用户权限查询

	@Override
	// 权限判断
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

		Users user = (Users)principalCollection.getPrimaryPrincipal();  // 获取已经登录的用户

		if(user != null){
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // 输出的权限凭证

			List<User_roles> roles = user_rolesMapper.selectByName(user.getUsername());

			for (User_roles role:roles) {
				String rolename = role.getRoleName();
				info.addRole(rolename); // 添加角色名称到凭证中
				List<Roles_permissions> permissions = roles_permissionsMapper.selectByRoleName(rolename);
				for (Roles_permissions permission:permissions) {
					info.addStringPermission(permission.getPermission()); // 添加角色的权限
				}

			}
			return info;
		}
		return null;
	}


	@Override
	// 登录判断
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; // 获取用户凭证
		System.out.println("开始登录:"+token.getUsername());

		Users user = usersMapper.selectByName(token.getUsername()); // 通过名称查询出用户

		System.out.println("user:"+user.getUsername());
		
		if(user != null){
			// 将用户与密码进行匹配
			SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
			
			// 输出匹配结果
			return simpleAuthenticationInfo;
		}
		// 为空则拦截信息
		return null;
	}

}
